#include "UnityCG.cginc"
#include "VertexCommon.hlsl"
#include "ZBufferCommon.hlsl"

sampler2D _MainTex;
float4 _MainTex_TexelSize;

int KernelRadius;
float DeltaR;
float DeltaD;

float4 frag(FS_IN i) : SV_Target {
	float3 vNorm = 0;
	float vDepth = GetDepthNormal(i.uv, vNorm);

	float sum = 0;
	float totalWeight = 0;
	for (int y = -KernelRadius; y <= KernelRadius; y++) {
		for (int x = -KernelRadius; x <= KernelRadius; x++) {
			float2 uv = i.uv + float2(x, y) / _MainTex_TexelSize.zw;
			if (all(0 <= uv) && all(uv <= 1)) {
				float3 vNormSample = 0;
				float vDepthSample = GetDepthNormal(uv, vNormSample);
				float weight = - (x*x + y*y)/(2 * DeltaD * DeltaD) - pow(vDepthSample - vDepth, 2)/(2 * DeltaR * DeltaR);
				weight = exp(weight);
				totalWeight += weight;
				sum += weight * tex2D(_MainTex, uv).r;
			}
		}
	}
	sum /= totalWeight;
	return float4(sum, sum, sum, 1);
}